package org.domain.seam1.session;

import javax.faces.application.FacesMessage;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.print.attribute.standard.Severity;

import org.domain.seam1.entity.User;
import org.domain.seam1.entity.Role;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

@Name("authenticator")
public class Authenticator {
	@Logger
	private Log log;

	@In
	Identity identity;
	@In
	Credentials credentials;
	@In
	private EntityManager entityManager;
	@In
	StatusMessages statusMessages;
	@In
	FacesMessages facesMessages;

	public boolean authenticate() {
		log.info("authenticating {0}", credentials.getUsername());
		// write your authentication logic here,
		// return true if the authentication was
		// successful, false otherwise

		if ("admin".equals(credentials.getUsername())) {
			identity.addRole("admin");
			return true;
		}

		User user;
		
		try {
			user = (User) entityManager
					.createQuery(
							"select user from User user where username = #{credentials.username}")
					.getSingleResult();
		} catch (NoResultException e) {
			e.printStackTrace();
			statusMessages.add(StatusMessage.Severity.ERROR,
					"No user has the username '#0'", credentials.getUsername());
			return false;
		}

		if (user != null) {
			if (user.getPassword().equals(credentials.getPassword())) {
				for (Role role : user.getRoles())
					identity.addRole(role.getRolename());
				identity.addRole("admin");
				return true;
			} else {
				return false;
			}
		}

		else {
			return false;
		}
	}

}
